const router = require('koa-router')()
const util = require('../utils/index.js')
const Menu = require('../models/menuSchema.js')

router.prefix('/api/menu')

router.get('/list', async (ctx) => {
    const { menuName, menuState } = ctx.request.query
    const params = {}
    if (menuName) params.menuName = menuName
    if (menuState) params.menuState = menuState
    let rootList = await Menu.find(params) || []
    if (menuName) {
        ctx.body = util.success(rootList, '')
    } else {
        // [] 这里是一个引用类型，会随着变化而变化
        const permissionList = util.getTreeMenu(rootList, null, [])
        ctx.body = util.success(permissionList, '')
    }
})

// 新增
router.post('/add', async (ctx, next) => {
    try {
        const { _id, ...params } = ctx.request.body
        let res = await Menu.create(params)
        ctx.body = util.success({}, '创建成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 编辑
router.post('/update', async (ctx, next) => {
    try {
        const { _id, ...params } = ctx.request.body
        params.updateTime = new Date()
        let res = await Menu.findByIdAndUpdate(_id, params)
        ctx.body = util.success({}, '更新成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

// 删除
router.post('/delete', async (ctx, next) => {
    try {
        const { _id } = ctx.request.body
        let res = await Menu.findByIdAndRemove(_id)
        // 删除包含_id的所有文档
        await Menu.deleteMany({ parentId: { $all: [_id] } })
        ctx.body = util.success({}, '删除成功')
    } catch (error) {
        ctx.body = util.fail(error.stack)
    }
})

module.exports = router
